package org.abettor.pushbox.net;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.abettor.pushbox.config.Config;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.util.Log;

/**
 * 网络工具
 * 
 * @author jzh
 * 
 */
public class NetTools {
	private HttpClient httpclient = null;

	/**
	 * 获得二进制的数据
	 * 
	 * @param url
	 * @param map
	 * @return
	 */
	public byte[] postDataStream(String url, Map<String, String> map) {
		try {
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(params,
					Config.httpTimeOut);
			HttpConnectionParams.setSoTimeout(params, Config.httpSoTimeOut);
			HttpConnectionParams.setSocketBufferSize(params,
					Config.httpBufferSize);
			HttpPost httpPost = new HttpPost(url);
			// 加入数据
			Set<Map.Entry<String, String>> entrySet = map.entrySet();
			List<NameValuePair> nameValueList = new ArrayList<NameValuePair>();
			Iterator<Map.Entry<String, String>> itr = entrySet.iterator();
			while (itr.hasNext()) {
				Map.Entry<String, String> entry = itr.next();
				String key = entry.getKey();
				String value = entry.getValue();
				nameValueList.add(new BasicNameValuePair(key, value));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nameValueList,"UTF-8"));
			httpclient = new DefaultHttpClient(params);
			// 提交请求
			HttpResponse response = httpclient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				httpPost.abort();
				return null;
			}
			// 获得数据
			HttpEntity httpEntity = response.getEntity();
			Header header = httpEntity.getContentEncoding();
			@SuppressWarnings("unused")
			String encode = null;
			if (header != null) {// 读取编码数据
				encode = header.getValue();
			}
			// 读取数据
			InputStream in = httpEntity.getContent();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int value = 0;
			while ((value = in.read()) != -1) {
				out.write(value);
			}
			byte[] buf = out.toByteArray();
			out.close();
			return buf;
		} catch (Exception e) {
		} finally {
			if (httpclient != null)
				httpclient.getConnectionManager().shutdown();
		}
		return null;
	}

	/**
	 * 提交数据
	 * 
	 * @return
	 */
	public String postData(String url, Map<String, String> map) {
		try {
			HttpParams params = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(params,
					Config.httpTimeOut);
			HttpConnectionParams.setSoTimeout(params, Config.httpSoTimeOut);
			HttpConnectionParams.setSocketBufferSize(params,
					Config.httpBufferSize);
			HttpPost httpPost = new HttpPost(url);
			// 加入数据
			Set<Map.Entry<String, String>> entrySet = map.entrySet();
			List<NameValuePair> nameValueList = new ArrayList<NameValuePair>();
			Iterator<Map.Entry<String, String>> itr = entrySet.iterator();
			while (itr.hasNext()) {
				Map.Entry<String, String> entry = itr.next();
				String key = entry.getKey();
				String value = entry.getValue();
				nameValueList.add(new BasicNameValuePair(key,value));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nameValueList,"UTF-8"));
			httpclient = new DefaultHttpClient(params);
			// 提交请求
			HttpResponse response = httpclient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				httpPost.abort();
				return null;
			}
			// 获得数据
			HttpEntity httpEntity = response.getEntity();
			Header header = httpEntity.getContentEncoding();
			String encode = null;
			if (header != null) {// 读取编码数据
				encode = header.getValue();
			}
			// 读取数据
			InputStream in = httpEntity.getContent();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int value = 0;
			while ((value = in.read()) != -1) {
				out.write(value);
			}
			byte[] buf = out.toByteArray();
			if (encode == null)
				return new String(buf);
			else
				return new String(buf, encode);
		} catch (Exception e) {
			Log.e(this.getClass().getName(), "", e);
		} finally {
			if (httpclient != null)
				httpclient.getConnectionManager().shutdown();
		}
		return null;
	}

	/**
	 * 上传二进制的名字
	 * 
	 * @param url
	 * @return
	 */
	public String postFile(String sUrl, String filename, String filecontentype,
			byte[] buffer, Map<String, String> map) {
		String boundary = "----------------ERDFGYHUIJKI";
		String end = "\r\n";
		String twoHyphens = "--";
		try {
			URL url = new URL(sUrl);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			httpURLConnection.setConnectTimeout(Config.httpTimeOut);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			httpURLConnection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			DataOutputStream dos = new DataOutputStream(
					httpURLConnection.getOutputStream());
			// 写入携带的其他数据
			if (map != null) {
				Set<Map.Entry<String, String>> entrySet = map.entrySet();
				Iterator<Map.Entry<String, String>> itr = entrySet.iterator();
				while (itr.hasNext()) {
					Map.Entry<String, String> entry = itr.next();
					String key = entry.getKey();
					String value = entry.getValue();
					if (value != null) {
						dos.writeBytes(twoHyphens + boundary + end);
						dos.writeBytes("Content-Disposition: form-data; name=\""
								+ key + "\"" + end);
						dos.writeBytes(end);
						dos.write(value.getBytes("UTF-8"));
						dos.writeBytes(end); 
					}
				}
			}
			dos.writeBytes(twoHyphens + boundary + end);
			dos.writeBytes("Content-Disposition: form-data; name=\"" + filename
					+ "\"; filename=\"file.map\"" + end);
			dos.writeBytes("Content-Type: " + filecontentype + end);
			dos.writeBytes(end);
			// 写文件的操作
			dos.write(buffer);
			// 写结束的操作符
			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			dos.flush();
			// 读取文件
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					httpURLConnection.getInputStream()));
			String content = "";
			String line;
			while ((line = rd.readLine()) != null) {
				content += line + "\r\n";
			}
			dos.close();
			rd.close();
			if ("".equals(content)) {
				return null;
			}
			return content;
		} catch (Exception e) {
			System.out.println(e);
		}
		return null;
	}
}
